package com.tuanbiao.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.CallSuper;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Lifecycle;
import androidx.viewbinding.ViewBinding;

import com.abiao.lib_utils.ActivityUtils;
import com.abiao.lib_utils.KeyboardUtils;
import com.hzjq.lib.BlastKool;
import com.hzjq.lib.callback.Interceptor;
import com.tuanbiao.R;
import com.tuanbiao.base.action.ActivityAction;
import com.tuanbiao.base.action.BundleAction;
import com.tuanbiao.base.action.HandlerAction;
import com.tuanbiao.base.action.ToastAction;
import com.tuanbiao.dialog.MessageDialog;
import com.tuanbiao.events.LoginValidEvent;
import com.tuanbiao.ui.SplashActivity;
import com.tuanbiao.ui.account.LoginActivity;
import com.tuanbiao.ui.blast.BlastActivity;
import com.tuanbiao.ui.blast.BlastNettedActivity;
import com.tuanbiao.utils.SPHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import me.jessyan.autosize.internal.CustomAdapt;
import timber.log.Timber;

/**
 * @author abiao
 * @since 2022/4/2 17:29
 */
public abstract class BaseActivity<B extends ViewBinding> extends AppCompatActivity implements
        ActivityAction, BundleAction, HandlerAction, ToastAction, CustomAdapt {
    protected final String TAG = this.getClass().getSimpleName();
    protected B binding;
    private PowerManager.WakeLock mWakeLock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setInterceptor();
        BlastKool.Companion.loader().onKeepAlive(this);
        if (userEventbus()) {
            EventBus.getDefault().register(this);
        }
        initActivity();
    }

    protected void setInterceptor() {
//        BlastKool.Companion.loader().setInterceptor(null);
        BlastKool.Companion.loader().setInterceptor((type, code, msg) -> {
            Timber.i(TAG + "onInterceptor:" + type + ",code:" + code + ",msg:" + msg);
            Class<? extends Activity> aClass = getThis().getClass();
            if (type == Interceptor.Type.TX) {
                new MessageDialog.Builder(getActivity())
                        .setTitle(R.string.common_warning)
                        .setMessage(msg)
                        .setCancelable(false)
                        .setAlone(true)
                        .setListener(dialog -> {
                            if (aClass != SplashActivity.class) {
                                finish();
                            } else {
                                showShortCircuit(code == -26 || code == -68 || code == 1001);
                            }
                        }).show();
            } else {

                if (aClass != BlastNettedActivity.class && aClass != BlastActivity.class && aClass != SplashActivity.class && aClass != LoginActivity.class) {
                    new MessageDialog.Builder(ActivityUtils.getTopActivity())
                            .setTitle(R.string.common_warning)
                            .setMessage("登录已失效，请重新登录!")
                            .setAlone(true)
                            .setListener(dialog -> {
                                SPHelper.setLoginValid(false);
                                EventBus.getDefault().postSticky(new LoginValidEvent(false));
                            })
                            .show();
                }
            }
        });
    }

    //短路
    protected void showShortCircuit(boolean isClose) {

    }

    protected boolean userEventbus() {
        return false;
    }

    protected void initActivity() {
        initLayout();
        initView();
        initData();
    }

    /**
     * 创建Binding
     */
    protected abstract B getBindingView();

    /**
     * 初始化控件
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected void initData() {

    }

    protected void initLayout() {
        binding = getBindingView();
        if (null != binding) {
            initSoftKeyboard();
            setContentView(binding.getRoot());
        }
    }

    /**
     * 初始化软键盘
     */
    protected void initSoftKeyboard() {
        // 点击外部隐藏软键盘，提升用户体验
        getContentView().setOnClickListener(v -> {
            // 隐藏软键，避免内存泄漏
            KeyboardUtils.hideSoftInput(getThis());
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        BlastKool.Companion.loader().onKeepAlive(this);
    }

    @Override
    @CallSuper
    protected void onDestroy() {
        super.onDestroy();
        if (userEventbus()) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (Looper.myLooper() != Looper.getMainLooper()) {
            runOnUiThread(() -> {
                // 隐藏软键，避免内存泄漏
                KeyboardUtils.hideSoftInput(getThis());
            });
        } else {
            // 隐藏软键，避免内存泄漏
            KeyboardUtils.hideSoftInput(getThis());
        }
    }

    /**
     * 如果当前的 Activity（singleTop 启动模式） 被复用时会回调
     */
    @Override
    protected void onNewIntent(Intent intent) {
        Log.d(TAG, "onNewIntent");
        super.onNewIntent(intent);
        // 设置为当前的 Intent，避免 Activity 被杀死后重启 Intent 还是最原先的那个
        setIntent(intent);
    }

    @Override
    public Bundle getBundle() {
        return getIntent().getExtras();
    }

    /**
     * 和 setContentView 对应的方法
     */
    public ViewGroup getContentView() {
        return findViewById(Window.ID_ANDROID_CONTENT);
    }

    @Override
    public Context getContext() {
        return this;
    }

    protected FragmentActivity getThis() {
        return this;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        for (Fragment fragment : fragments) {
            // 这个 Fragment 必须是 BaseFragment 的子类，并且处于可见状态
            if (!(fragment instanceof BaseFragment) ||
                    fragment.getLifecycle().getCurrentState() != Lifecycle.State.RESUMED) {
                continue;
            }
            // 将按键事件派发给 Fragment 进行处理
            if (((BaseFragment<?>) fragment).dispatchKeyEvent(event)) {
                // 如果 Fragment 拦截了这个事件，那么就不交给 Activity 处理
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean isBaseOnWidth() {
        return true;
    }

    @Override
    public float getSizeInDp() {
        return 360;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    protected String getString(TextView textView) {
        if (textView != null) {
            return textView.getText().toString().trim();
        }
        return "";
    }

    @ColorInt
    protected int getCompatColor(@ColorRes int id) {
        return ContextCompat.getColor(this, id);
    }

    protected View.OnClickListener getBackListener() {
        return v -> onBackPressed();
    }
}
